package com.cqwshzj.util;/**
 * @Description:
 * @Auther: Huang Zhijin
 * @Version: 1.0.0
 * @Date: 2021/4/7 14:13
 */

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 *
 * 〈〉
 *
 * @author Huang Zhijin
 * @create 2021/4/7
 * @since 1.0.0
 */
public class SysUtils {

	public static final Logger log = LoggerFactory.getLogger(SysUtils.class);

	private static final String EMPTY_JSON_STR ="{}";

	private static ObjectMapper OBJECT_MAPPER = null;

	static {
		OBJECT_MAPPER = new ObjectMapper();
	}


	public static String getCurDevId(){
		Enumeration<NetworkInterface> interfaces = null;
		String ip = "0.0.0.0";
		try {
			interfaces = NetworkInterface.getNetworkInterfaces();
		}catch (Exception e){
			log.error("failed to get the networkInterface : "+ e.getMessage(),e);
		}

		boolean found = false;
		while ( !found && interfaces.hasMoreElements() ){
			final NetworkInterface networkInterface = interfaces.nextElement();
			final Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
			while ( inetAddresses.hasMoreElements() ){
				final InetAddress inetAddress = inetAddresses.nextElement();
				ip = inetAddress.getHostAddress();
				if ( ip == null || ip.contains("0.0") || ip.contains("127.0.0")){
					continue;
				}
				if (log.isDebugEnabled()) {
					log.debug(" current dev_id[{}]", ip);
				}
				found = true;
				break;
			}
		}
		return ip;
	}

	//-----------------------------------------


	public static String obj2JsonStr(Object obj){
		if (obj == null) {
			return EMPTY_JSON_STR ;
		}
		try {
			return OBJECT_MAPPER.writeValueAsString(obj);
		}catch (Exception e){
			log.error("obj2JsonStr error. ",e );
			return EMPTY_JSON_STR;
		}
	}

	public static <T> T jsonStr2Obj(String jsonStr, Class<T> targetClass ){
		if (StringUtils.isEmpty( jsonStr )) {
			return null;
		}
		try {
			return OBJECT_MAPPER.readValue(jsonStr , targetClass );
		}catch (Exception e){
			log.error("jsonStr2Obj error. ",e);
			return null;
		}
	}




}
